package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;

/**
 * 二次注册
 * 医院信息绑定
 * @author Administrator
 *
 */
public class Registeruserinfo extends Activity {
	private Registeruserinfo oThis = this;
	private EditText  realname, pcard,phoneno,jzcard,checkmessage;
	private Button saveButton,messagebutton;
	private ImageButton cancelButton;
	private ProgressDialog proDialog;
	private boolean flag = true;
	InputMethodManager manager;
	private RadioGroup sex;
	MyApplication application;
	private ImageButton mainselected;
	private String name="",card="",sexv="",phone="",user_id="",user_jzcard="";
	private String state = "";
	private Timer timer;//计时器
	private int count = 300;//记录时间，短信验证60秒内不能再次发送
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.registeruserinfo);
		application = (MyApplication) getApplication();
		application.addActivity(this);
		manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		// 得到相应的显示控件的对象
		
		realname = (EditText) findViewById(R.id.realname);
		pcard = (EditText) findViewById(R.id.pcard);
		sex = (RadioGroup)findViewById(R.id.sex);  
		phoneno = (EditText) findViewById(R.id.phoneno);
		jzcard = (EditText) findViewById(R.id.jzcard);
		checkmessage = (EditText) findViewById(R.id.checkmessage);
		
		realname.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		pcard.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		phoneno.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		jzcard.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		checkmessage.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		
		Intent intent = getIntent();
		user_id = intent.getStringExtra("user_id");
		name =intent.getStringExtra("user_mc");
		card =intent.getStringExtra("user_sfzh");
		phone =intent.getStringExtra("user_sjh");
		sexv =intent.getStringExtra("user_xb");
		user_jzcard = intent.getStringExtra("user_jzcard");
		
		if(!card.equals("")){
			realname.setText(name);
			pcard.setText(card);
			phoneno.setText(phone);
			if(sexv.equals("1")){
				sex.check(R.id.boy);
			}else{
				sex.check(R.id.girl);
			}
			jzcard.setText(user_jzcard);
		}
		
		if(application.getJzhflag()!=null&&application.getJzhflag().equals("1")){
			jzcard.setVisibility(View.VISIBLE);
		}else{
			jzcard.setVisibility(View.GONE);
		}
		messagebutton = (Button) findViewById(R.id.messagebutton);
		saveButton = (Button) findViewById(R.id.save_button);
		mainselected = (ImageButton) this.findViewById(R.id.mainselected);
		cancelButton = (ImageButton) findViewById(R.id.imageback);
		cancelButton.setClickable(true);
		
		if(application.getMessageflag()!=null&&application.getMessageflag().equals("1")){//短信验证开启
			messagebutton.setVisibility(View.VISIBLE);
			checkmessage.setVisibility(View.VISIBLE);
		}else{
			messagebutton.setVisibility(View.GONE);
			checkmessage.setVisibility(View.GONE);
		}
		
		messagebutton.setOnClickListener(new View.OnClickListener() {
			// 当按钮被点击时调用该方法
			public void onClick(View v) {
				//获取短信验证码
				if (phoneno.getText().toString().length() == 0) {
						Toast.makeText(Registeruserinfo.this, "请先输入手机号码", Toast.LENGTH_SHORT)
						.show();
				}else{
					count=60;
					messagebutton.setEnabled(false);
	                timer=new Timer();
	                timer.schedule(new TimerTask()
	                {
	                        
	                        @Override
	                        public void run()
	                        {
	                                handler.sendEmptyMessage(count--);
	                        }
	                }, 0, 1000);
					addMessage();
				}
			}
		});
		
		// 为saveButton 注册一个点击事件监听器
		saveButton.setOnClickListener(new View.OnClickListener() {
			// 当按钮被点击时调用该方法
			public void onClick(View v) {
				addUser();
			}
		});

		cancelButton.setOnClickListener(new View.OnClickListener() {
			// 当按钮被点击时调用该方法
			public void onClick(View v) {
				oThis.onBackPressed();
			}
		});
		mainselected.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(oThis, Mainmean.class);
				startActivity(intent);
				oThis.finish();
			}
		});
//		Log.e("", application.getDeviceId());
	}
	
	private Handler  handler=new Handler(){
        public void handleMessage(android.os.Message msg) {
                if(msg.what==0){
                	messagebutton.setEnabled(true);
                	timer.cancel();
                	messagebutton.setText("发送");
                }else{
                	messagebutton.setText(msg.what+"秒");
                }
    };
    };

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				manager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}
	
	public static OnFocusChangeListener onFocusAutoClearHintListener = new OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			EditText textView = (EditText) v;
			String hint;
			if (hasFocus) {
				hint = textView.getHint().toString();
				textView.setTag(hint);
				textView.setHint("");
			} else {
				hint = textView.getTag().toString();
				textView.setHint(hint);
			}
		}
	};

	/**
	* 拼写检测，检测输入内容是否合乎要求
	*/
	public void addUser() {
		int ecolor = Color.RED; // whatever color you want
		String estring = "";
		ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
		
		if (realname.getText().toString().length() == 0) {
			estring = "真实姓名不能为空";
			SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
			ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
			realname.setError(ssbuilder);
		} else if (pcard.getText().toString().length() == 0) {
			estring = "身份证号不能为空";
			SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
			ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
			pcard.setError(ssbuilder);
		}else if (phoneno.getText().toString().length() == 0) {
			estring = "手机号不能为空";
			SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
			ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
			phoneno.setError(ssbuilder);
		}else if(checkmessage.getText().toString().length() == 0&&application.getMessageflag()!=null&&application.getMessageflag().equals("1")){
				estring = "验证码不能为空";
				SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
				ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
				checkmessage.setError(ssbuilder);
		}else {
			proDialog = ProgressDialog.show(Registeruserinfo.this, "", "保存中...", true,
					true);

			String registerInfo = registerUser();
			if (registerInfo.equals("SAVE_SUCCESS")||registerInfo.equals("MARRY_NOTSUCCESS")) {
				application.setHzxm(realname.getText().toString().trim());
				application.setSfzh(pcard.getText().toString().trim());
				application.setSjh(phoneno.getText().toString().trim());
				application.setJzcard(jzcard.getText().toString().trim());
				application.setSex(sexv);
				application.setMemberid(user_id);
				
				//把选择的成员加入缓存
				SharedPreferences settings = getSharedPreferences("users_file", 0);
				//获得可编辑对象
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("drzh",application.getAccount());
				editor.putString("username",realname.getText().toString().trim());
				editor.putString("sfzh", pcard.getText().toString().trim());
				editor.putString("sjh", phoneno.getText().toString().trim());
				editor.putString("jzcard", jzcard.getText().toString().trim());
				editor.putString("xb", sexv);
				editor.putString("memberid", user_id);//家庭成员id
				editor.commit();
				
				if(state.equals("2")){
					Toast.makeText(Registeruserinfo.this, "保存成功", Toast.LENGTH_SHORT)
					.show();
				}else{
					Toast.makeText(Registeruserinfo.this, "保存成功,但未能与医院信息匹配", Toast.LENGTH_SHORT)
					.show();
				}
				application.getServiceManager().stopService();
				application.getServiceManager().startService();

				
				// 到下一页面
				Intent intent = new Intent();
				intent.setClass(Registeruserinfo.this, Mainmean.class);
				application.setActiveFlag("yes");
				startActivity(intent);
				oThis.finish();
			}else if (registerInfo.equals("CHECK_NOTSUCCESS")) {
				Toast.makeText(Registeruserinfo.this, "验证码验证失败", Toast.LENGTH_SHORT)
				.show();
			} else if (registerInfo.equals("SAVE_NOTSUCCESS")) {
				Toast.makeText(Registeruserinfo.this, "保存失败", Toast.LENGTH_SHORT)
						.show();
			}
			proDialog.dismiss();
		}
	}

	/**
	 * 注册用户
	 */
	public String registerUser() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id", user_id));//用户记录id，空为新增，否则为修改
		params.add(new BasicNameValuePair("userid", application.getAccount()));
		params.add(new BasicNameValuePair("realname", realname.getText()
				.toString().trim()));
		params.add(new BasicNameValuePair("pcard", pcard.getText().toString()
				.trim()));
		params.add(new BasicNameValuePair("phoneno", phoneno.getText().toString()
				.trim()));
		params.add(new BasicNameValuePair("jzcard", jzcard.getText().toString()
				.trim()));
		params.add(new BasicNameValuePair("messageflag", application.getMessageflag()));//短信验证码开启标志
		params.add(new BasicNameValuePair("checkmessage", checkmessage.getText().toString()
				.trim()));//短信验证码
		
		String temp ="";
		for(int i=0; i<sex.getChildCount(); i++){  
            RadioButton r = (RadioButton)sex.getChildAt(i);  
            if(r.isChecked()){  
            	temp = r.getText().toString();  
            	if(temp.equals("男")){
            		temp = "1";
            	}else{
            		temp = "0";
            	}
                break;  
            }  
        }  
		sexv = temp;
		params.add(new BasicNameValuePair("sex", temp));
		JSONObject res = HTTPGetTool.getTool().post(
				URLUtils.HOST + URLUtils.URLREGISTERUSER, params);
		String registerInfo = "SAVE_NOTSUCCESS";
		if (res != null) {
			try {
				registerInfo = res.get("registerInfo").toString();
				if (registerInfo.equals("CHECK_NOTSUCCESS")){//验证码验证失败
					state = "";
					user_id = "";//保存成功后返回成员id
				}else{
					state = res.get("rigisterstate").toString();
					user_id = res.get("id").toString();//保存成功后返回成员id
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return registerInfo;
	}
	
	/**
	* 获取验证码
	*/
	public void addMessage() {
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("phoneno", phoneno.getText().toString()
				.trim()));
		//产生短信验证码，并保存到数据库
		JSONObject res = HTTPGetTool.getTool().post(
				URLUtils.HOST + URLUtils.URLGETMESSAGE, params);
		String message = "";
		if (res != null) {
			try {
				message = res.get("message").toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (!message.equals("")) {//验证码保存成功，则发送短信
			List<NameValuePair> lsparams = new ArrayList<NameValuePair>();
			lsparams.add(new BasicNameValuePair("phone", phoneno.getText().toString()
					.trim()));
			lsparams.add(new BasicNameValuePair("message", message));//短信验证码
			JSONObject sendres = HTTPGetTool.getTool().post(
					URLUtils.HOST + URLUtils.URLSENDMESSAGE, lsparams);
			if (sendres != null) {
				String sendflag = "1";
				try {
					sendflag = sendres.get("sendInfo").toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(sendflag.equals("0")){
					Toast.makeText(Registeruserinfo.this, "验证码已经发送,请注意查看手机", Toast.LENGTH_SHORT)
					.show();
				}else{
					Toast.makeText(Registeruserinfo.this, "验证码发送失败,错误码"+sendflag, Toast.LENGTH_SHORT)
					.show();
				}
			}
			
		}
		
	}
	
	@Override
    public void onDestroy()
    {
            if(timer!=null)
                    timer.cancel();
            super.onDestroy();
    }

}